﻿using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Reflection;

namespace FYSJcrm.Core.Web.Extensions.ServiceExtensions
{
    public static class InjectHelper
    {
        public static void AddTransient(this IServiceCollection services, Assembly interfaceAssembly, Assembly implementAssembly)
        {
            var interfaces = interfaceAssembly.GetTypes().Where(p => p.IsInterface);
            var implements = implementAssembly.GetTypes();

            foreach (var item in interfaces)
            {
                var type = implements.FirstOrDefault(p => item.IsAssignableFrom(p));
                if (type != null)
                {
                    services.AddTransient(item, type);
                }
            }
        }

        public static void AddScoped(this IServiceCollection services, Assembly interfaceAssembly, Assembly implementAssembly)
        {
            var interfaces = interfaceAssembly.GetTypes().Where(p => p.IsInterface);
            var implements = implementAssembly.GetTypes();

            foreach (var item in interfaces)
            {
                var type = implements.FirstOrDefault(p => item.IsAssignableFrom(p));
                if (type != null)
                {
                    services.AddScoped(item, type);
                }
            }
        }
    }
}
